package cn.jsc.pay.utils;

import cn.jsc.pay.config.AlipayConfig;
import cn.jsc.pay.domain.AlipayInfo;
import cn.jsc.pay.domain.PayBill;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

/**
 * 支付宝支付的工具类
 */
public class AlipayUtil {
    public static String pay(AlipayInfo alipayInfo, PayBill payBill){
        /**
         * 支付
         * @param alipayInfo  支付宝信息【appid,公钥，私钥】
         * @param payBill  支付单【金额，支付唯一标识，交易摘要】
         * @return
         */
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                    alipayInfo.getAppid(),
                    alipayInfo.getMerchant_private_key(), "json",
                    AlipayConfig.charset,
                    alipayInfo.getAlipay_public_key(),
                    AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = payBill.getUnionPaySn();
            //付款金额，必填
            String total_amount = payBill.getMoney().toString();
            //订单名称，必填
            String subject = payBill.getDigest();
            //商品描述，可空
            String body = payBill.getDigest();

            //通过支付宝的公钥进行加密，再通过自己的私钥进行就加密[RSA2]
            //加密：先使用对方的公钥进行加密，再用自己的私钥进行二次加密（数字签名），
            //解密：先使用对方的公钥进行解密（签名认证），再使用自己的私钥进行解密。
            /**
             *  + "\"timeout_express\":\""+ "15m" +"\","  设置最晚支付时间，逾期关闭交易
             *     15分钟后关闭交易
             */
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"timeout_express\":\""+ "15m" +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
